package com.gobuy.page.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gobuy.common.pojo.Result;
import com.gobuy.goods.feign.CategoryFeign;
import com.gobuy.goods.feign.SkuFeign;
import com.gobuy.goods.feign.SpuFeign;
import com.gobuy.goods.pojo.Category;
import com.gobuy.goods.pojo.Sku;
import com.gobuy.goods.pojo.Spu;
import com.gobuy.page.service.PageService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Gaozexi on 2020/6/11 0:17
 * Step by Step  and Stand on,  You Are The Best Investment!
 */
@Service
public class PageServiceImpl implements PageService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private CategoryFeign categoryFeign;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SkuFeign skuFeign;
    @Value("${pagepath}")
    private String pagePath;

    @Autowired
    private TemplateEngine templateEngine;


    @Override
    public void generateItemPage(String spuId) {
        //获取Context对象 ,存放商品详情数据
        Context context = new Context();
        Map<String, Object> itemData = this.findItemDataBySpuId(spuId);
        context.setVariables(itemData);

        //获取商品详情页的生成位置
        File dir = new File(pagePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //定义输出流,进行文件创建
        File file = new File(dir + "/" + spuId + ".html");
        Writer writer = null;
        try {
            writer = new PrintWriter(file);
            //生成文件
            /**
             *  1模板文件名称
             *  2context对象,加载模板需要的数据
             *  3输出流,指定输出位置
             * **/
            templateEngine.process("item", context, writer);
            logger.info("商品"+spuId+"详情页生成成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteItemPage(String spuId) {
        File dir =null;
        try{
            dir= new File(pagePath + "/" + spuId);

        }catch(Exception e){

        }
        if(dir!=null){
            boolean delete = dir.delete();
            if (delete == true) {
                logger.info("商品" + spuId + "详情页删除成功");
            } else {
                logger.error("商品" + spuId + "详情页删除失败");
            }
        }


    }


    //获取静态页面需要的数据
    public Map<String, Object> findItemDataBySpuId(String spuId) {
        Map<String, Object> resultMap = new HashMap<>(16);
        Result<Spu> spuResult = spuFeign.findSpuById(spuId);
        Spu spu = spuResult.getData();
        if (spu != null) {
            //商品详情的图片信息
            if (!StringUtils.isEmpty(spu.getImages())) {
                resultMap.put("imageList", spu.getImages().split(","));
            }
        }
        //获取分类信息
        Category category1 = categoryFeign.findById(spu.getCategory1Id()).getData();
        Category category2 = categoryFeign.findById(spu.getCategory2Id()).getData();
        Category category3 = categoryFeign.findById(spu.getCategory3Id()).getData();
        resultMap.put("category1", category1);
        resultMap.put("category2", category2);
        resultMap.put("category3", category3);
        //获取sku信息
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        resultMap.put("skuList", skuList);
        resultMap.put("spu",spu);
        //商品规格信息
        try {
            resultMap.put("specificationList", objectMapper.readValue(spu.getSpecItems(), Map.class));
        } catch (JsonProcessingException e) {
            System.out.println("JSON转换异常");
            e.printStackTrace();
        }
        return resultMap;
    }
}
